﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using NuSoft.SistemaGestionPersonal.WinFormsUI.BusinessEntities;

namespace NuSoft.SistemaGestionPersonal.WinFormsUI
{
    public class Repository
    {
        private const string _FileName = @"NuSoft.SistemaGestionPersonal.xml";

        private static readonly XmlSerializer _XmlSerializer = new XmlSerializer(typeof(Repository));

        private static readonly Lazy<Repository> _Instance = new Lazy<Repository>(() =>
        {
            Repository result;

            if (File.Exists(_FileName))
            {
                using (var streamReader = new StreamReader(_FileName))
                {
                    result = (Repository)_XmlSerializer.Deserialize(streamReader);
                }

                if (result.Employees == null)
                {
                    result.Employees = new List<Employee>();
                }

                if (result.Positions == null)
                {
                    result.Positions = new List<Position>();
                }
            }
            else
            {
                result = new Repository { Employees = new List<Employee>(), Positions = new List<Position>() };
                result.Persist();
            }

            return result;
        });

        public List<Employee> Employees { get; set; }
        public List<Position> Positions { get; set; }
        
        private Repository()
        {            
        }

        public static Repository Instance
        {
            get { return _Instance.Value; }
        }

        public void Persist()
        {
            if (!File.Exists(_FileName))
            {
                File.Create(_FileName).Close();
            }

            using (var streamWriter = new StreamWriter(_FileName))
            {
                _XmlSerializer.Serialize(streamWriter, this);
            }
        }
    }
}